package com.caijb.netty.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/8/24 10:42
 */
public class BioClient {
    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;
    private Scanner scanner;

    public BioClient(String host, int port) throws IOException {
        // 连接服务端
        socket = new Socket(host, port);
        // 初始化输入输出流
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintWriter(socket.getOutputStream(), true);
        scanner = new Scanner(System.in);
        System.out.println("Connected to server: " + host + ":" + port);
    }

    public void start() {
        // 启动读取消息的线程
        Thread readThread = new Thread(this::readMessages);
        readThread.setDaemon(true);
        readThread.start();

        // 主线程处理用户输入
        try {
            String serverMessage = reader.readLine();
            System.out.println("Server: " + serverMessage);

            System.out.println("Start chatting (type 'bye' to exit):");
            String userInput;
            while ((userInput = scanner.nextLine()) != null) {
                writer.println(userInput);
                if ("bye".equalsIgnoreCase(userInput.trim())) {
                    break;
                }
            }
        } catch (IOException e) {
            System.err.println("Error in client: " + e.getMessage());
        } finally {
            closeResources();
        }
    }

    private void readMessages() {
        try {
            String message;
            while ((message = reader.readLine()) != null) {
                System.out.println("Server response: " + message);
            }
        } catch (IOException e) {
            if (!socket.isClosed()) {
                System.err.println("Error reading from server: " + e.getMessage());
            }
        }
    }

    private void closeResources() {
        try {
            if (scanner != null) scanner.close();
            if (reader != null) reader.close();
            if (writer != null) writer.close();
            if (socket != null) socket.close();
            System.out.println("Client disconnected");
        } catch (IOException e) {
            System.err.println("Error closing client resources: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        try {
            BioClient client = new BioClient("localhost", 8080);
            client.start();
        } catch (IOException e) {
            System.err.println("Failed to connect to server: " + e.getMessage());
        }
    }
}
